<?php

namespace app\service;

use app\dao\AdminDao;
use app\dao\StudentDao;
use app\model\Student;
use app\utils\encryption;
use app\utils\jwt;
use think\exception\ValidateException;
use think\facade\Cache;

class AuthService
{
    private $studentDao;
    private $adminDao;

    public function __construct()
    {
        $this->adminDao = new AdminDao();
        $this->studentDao = new StudentDao();
    }

    public function LoginCheck($username , $password , $type = 'admin'){
        switch ($type){
            case "admin" :
                $dao = $this->adminDao;
                $jwt = new jwt('admin');
                break;
            case "student" :
                $dao = $this->studentDao;
                $jwt = new jwt('student');
                break;
            default :
//                throw new
                break;
        }
        try {
            $result = $dao->findByUsername($username)
                ->findByPassword(encryption::getPassword($password))
                ->getOne();
            if ($result == null) throw new ValidateException("账号或密码错误!");
            unset($result->password);       // 移除password
            $result->token = $jwt->signToken($result->id);      // 生成token
            Cache::store("redis")->set("user:$result->id-role:$type:token" , $result->token , 60 * 60 * 24);      // redis缓存token
        }catch (\Exception $exception){
//            throw new
        }
        return $result;     // 将结果返回
    }

    public function Register($username , $password){
        if ($this->studentDao->findByUsername($username)->getOne() != null) throw new ValidateException("该用户名已有用户注册!");
        try{
            $result = $this->studentDao->create([
                'username' => $username,
                'password' => encryption::getPassword($password),
                'nickname' => $username,
                'head_img' => env('DEFAULT.STUDENT_HEAD_IMG' , null)
            ]);
        }catch (\Exception $exception){
//            throw new
        }
        unset($result->password);       // 移除password
        return $result;
    }
}